import requests
import execjs
import pandas as pd
headers = {
    'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36',
    'cookie':'UserId=17509508975793163; Hm_lvt_ab6a683aa97a52202eab5b3a9042a8d2=1750950899; Hm_lpvt_ab6a683aa97a52202eab5b3a9042a8d2=1750951031; Hm_lvt_7c50c7060f1f743bccf8c150a646e90a=1750951153; HMACCOUNT=8CE78798304DFB22; Hm_lvt_30606b57e40fddacb2c26d2b789efbcb=1750951163; Hm_lpvt_30606b57e40fddacb2c26d2b789efbcb=1750951163; Hm_lvt_601d681fcf2fa8574658a1b81b7dfb20=1750951163; PATHURL=c=code&id=16&color=%23cfa8cf&bdc=%23964596&icon=3&site=16&lang=cn; Hm_lpvt_601d681fcf2fa8574658a1b81b7dfb20=1750951590; Hm_lpvt_7c50c7060f1f743bccf8c150a646e90a=1750951590',
    'referer':'https://lishi.tianqi.com/chongqing/202501.html'
}

url_new = 'https://lishi.tianqi.com/monthdata/chongqing/202505'
# data = {'crypte':'9XH60LqEQ3%2BGgEDtZ1VZVfZM6H8mYsQqVm6YdjUSI7k%3D'}   # 直接用参数调用，返回为空，请求参数逆向分析

# 获取加密参数，用python调用js代码

city = "chongqing";
crypte = execjs.compile(open('weather.js',encoding='utf-8').read()).call('getsign',city)
data = {'crypte':crypte}
'''请求参数逆向分析：
1.通过开发者定位加密位置：
方法1： xhr 断点跟栈
方法2： 关键字搜索（根据加密参数名称搜索，已试过）
方法3： hook
方法4：根据启动器(initiator，response右边)跟栈   （在这里选此种方式，方便，效果与关键字搜索一致，然后打断点）
。。。
'''


resp_new = requests.post(url = url_new,headers=headers,data=data)
resp_new.encoding = 'utf-8'
json_data = resp_new.json()
data = []
for i in json_data:
    data.append({
        '日期':i['_id'][i.get('_id').index('_')+1:],
        '风向':i['WD'],
        '风力': i['WS'],
        '最高温度/最低温度': str(i['max_htemp']) + '/' + str(i['min_ltemp']),
        '天气状况': i['weather']
    })
print(data)
df = pd.DataFrame(data)
df.to_excel('output.xlsx',index=False,engine='openpyxl')
